<template>
  <div>
  <ul class="timebank-box" v-if="api =='timebank_volunteerNum'">
    <li v-for="(item,index) in areaColorList" :key="index">
      <p :style="{background:item.itemStyle.areaColor}">&nbsp;</p>
      <span>{{ item.name }}({{ item.num }}人)</span>
      <!-- {{ item.itemStyle.areaColor }} -->
    </li>
  </ul>
    <AplidCharts
      ref="mapEl"
      type="map"
      :timeLoad="false"
      mapName="nanjing_outline,nanjing"
      :option="option"
      style="width: 100%; height: 100%"
    ></AplidCharts>

    <AplidDialog
      width="310px"
      :showModel="false"
      v-model="visible"
      :title="title"
      style="
        --dialog-background: rgba(0, 0, 0, 0.6);
        --dialog-header-background: rgba(253, 189, 0, 0.5);
      "
    >
      <div v-if="visible" :key="reloadKey">
        <PageOrg
          v-if="activeTab == 1 || api == 'largeScreen_orgList'"
          :nowRowData="nowRowData"
        ></PageOrg>
        <PageOrder v-else-if="api" :nowRowData="nowRowData"></PageOrder>
        <PageFact v-else :nowRowData="nowRowData"></PageFact>
      </div>
    </AplidDialog>
  </div>
</template>

<script setup lang="ts">
import iconPoint from "@/assets/icon-point-v1.png";
// import iconPoint from "@/assets/imgs/icon-point.png";
import iconPointVR from "@/assets/icon-point-vr-1.png";
// import iconPointVR from "@/assets/imgs/icon-vr.webp";
import iconPointOrder from "@/assets/imgs/icon-point-order.png";
import iconMarkerOne from "@/assets/imgs/icon-point1.png";
import PageOrg from "./PageOrg.vue";
import PageFact from "./PageFact.vue";
import PageOrder from "./PageOrder.vue";
import areaJson from "@/assets/data/areaOrder.json";
import apiMod from "@/apiMod";
import { isWithinNanjing } from "@/utils/index";

const props = defineProps<{
  activeTab?: any;
  api?: string;
  paramsObj?: any;
}>();
const reloadKey = ref(0);
const title = ref("");
const nowRowData: any = ref({});
const mapEl = ref(null);
const visible = ref(false);
const areaColorList = ref([])
const BaseOption = (
  data?: any,
  icon?: any,
  symbolSize?: any,
  mapAreaData?: any
) => {
  const option = {
    tooltip: {
      trigger: "item",
      formatter: (params) => {
        const data = params.data || {};
        const name = data.organizationName || data.soleValue;
        if (name) return `<p>${name}</p>`;
      },
    },
    xAxis: {
      show: false,
    },
    yAxis: {
      show: false,
    },
    animation: true,
    grid: {
      top: 0,
    },
    geo: [
      {
        map: "nanjing_outline",
        aspectScale: 0.75,
        zoom: 1.2, // 缩放
        zlevel: -1,
        roam: false,
        silent: true,
        layoutCenter: ["50%", "50%"],
        layoutSize: "100%",
        itemStyle: {
          borderColor: "rgba(206, 213, 217, 1)",
          borderWidth: 2,
          shadowColor: "rgba(29, 109, 86, 1)",
          shadowOffsetX: 20,
          shadowOffsetY: 30,
          shadowBlur: 10,
          areaColor: "transparent",
          emphasis: {
            show: false,
          },
        },
        label: {
          emphasis: {
            show: false,
          },
        },
        transform: {
          rotateY: 90, // 设置地图倾斜角度
        },
      },
      // 重影
      {
        type: "map",
        map: "nanjing_outline",
        zlevel: -1,
        aspectScale: 0.75,
        zoom: 1.2, // 缩放
        layoutCenter: ["52%", "51%"],
        layoutSize: "100%",
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 2,
          borderColor: "rgba(206, 213, 217, 0.1)",
          shadowColor: "rgba(10, 79, 102, 0.4)",
          shadowOffsetY: 5,
          shadowBlur: 15,
          areaColor: "rgba(10, 79, 102, 0.2)",
          emphasis: {
            show: false,
          },
        },
        label: {
          emphasis: {
            show: false,
          },
        },
      },
    ],
    series: [
      {
        type: "map",
        map: "nanjing", // 自定义扩展图表类型
        aspectScale: 0.75,
        zoom: 1.2, // 缩放
        silent: true,
        zlevel: -1,
        label: {
          show: true,
          color: "rgba(255,255,255,0.6)",
          // backgroundColor: "rgba(253, 189, 0, 0.5)",
          padding: [14, 12],
          borderRadius: 5,
          lineHeight: 16,
          fontSize: 20,
          emphasis: {
            show: false,
          },
        },
        itemStyle: {
          areaColor: "rgba(20, 169, 218, 1)",
          borderColor: "#fff",
          borderWidth: 0.4,
          emphasis: {
            show: false,
            color: "#fff",
            areaColor: "rgba(41, 199, 130, 0.6)",
          },
        },
        layoutCenter: ["50%", "50%"],
        layoutSize: "100%",
        data: mapAreaData,
      },
      {
        type: "effectScatter",
        coordinateSystem: "geo",
        zlevel: 20,
        data: data,
        showEffectOn: "emphasis",
        rippleEffect: {
          scale: 4,
          brushType: "stroke",
        },
        symbol: function (params) {
          const item = data.find((item: any) => {
            return item.value?.toString() === params.toString();
          });
          if (item.vr_src) {
            return `image://${iconPointVR}`;
          } else {
            return `image://${icon ? icon : iconMarkerOne}`;
          }
        },
        symbolSize: function (params) {
          const item = data.find((item: any) => {
            return item.value?.toString() === params.toString();
          });
          if (item.vr_src) {
            return [48, 48];
          } else {
            return symbolSize ? symbolSize : [10, 10];
          }
        },
        // symbolSize: symbolSize ? symbolSize : [45, 45],
        label: {
          formatter: "{b}",
          position: "right",
          show: false,
        },
      },
    ],
  };
  return option;
};
const data = [];
const option = BaseOption(data);

const vrStrObj = {
  银城红日养老公寓:
    "https://web.xiaohongwu.com/hotspot/preview?p=d236ecf739d5424eb98813f1006885a8",
  南京瑞芝康健老年公寓:
    "https://web.xiaohongwu.com/hotspot/preview?p=51e44f650a7949e8b023f40eebaf4f00",
  银城康养三牌楼颐养中心:
    "https://web.xiaohongwu.com/hotspot/preview?p=63157ff7dbd54f09b1aa266d2b32c43e",
  太保家园南京颐养社区:
    "https://web.xiaohongwu.com/hotspot/preview?p=s-fa734ac70f2b4b3fb640390788f0f3ad&shareFrom=wx&shareMethod=link&shareType=1",
  "欧葆庭（南京）养老服务有限公司":
    "https://web.xiaohongwu.com/hotspot/preview?p=s-07484223ac6c491d861b1fda1fed109c&shareFrom=wx&shareMethod=link&shareType=1",
  建邺区社会福利院:
    "https://web.xiaohongwu.com/hotspot/preview?p=s-779bf114e02840c0a8695985d03d0835&shareFrom=wx&shareMethod=link&shareType=1",
};

const setMarkerData = (data?: any, type?: any) => {
  const markerList = data
    .map((item) => {
      const orgName = item.organizationName || item.soleValue;
      const isSet = isWithinNanjing(+item.lon, +item.lat);
      if (!isSet) return "";
      if (Object.keys(vrStrObj).includes(orgName)) {
        item.vr_src = vrStrObj[orgName];
      }

      if (orgName == "欧葆庭（南京）养老服务有限公司" && !item.legalUserName) {
        item.legalUserName = "黄宣尧";
        item.legalUserPhone = "15380838833";
      }
      const phone = item.legalUserPhone||item.personTelephone||item.serviceObjectPhone
      if(!phone) return ''
      return {
        ...item,
        value: [item.lon, item.lat],
      };
    })
    .filter(Boolean);

  const option = BaseOption(
    markerList,
    type ? iconPointOrder : iconPoint,
    [10, 10]
  );

  mapEl.value?.setOptions(option);
  mapEl.value?.myChart.on("click", (e: any) => {
    nowRowData.value = e.data || {};
    reloadKey.value = Math.random();
    console.log(e.data, "dd");
    if (type == "order") {
      title.value = `订单编号：${
        nowRowData.value.orderCard || nowRowData.value.orderNo
      }`;
    } else {
      title.value =
        nowRowData.value.organizationName || nowRowData.value.soleValue;
    }
    visible.value = true;
  });
};

const getInitData = () => {
  if (props.api) {
    if (props.api == "orderList") {
      Promise.all([
        apiMod.govOrderList({ limit: 50 }),
        apiMod.gl_orderservice({ limitSize: 50 }),
        apiMod.lh_orderservice({ limitSize: 50 }),
      ])
        .then((res) => {
          return res.map((item) => item.data);
        })
        .then((res) => {
          const areaData = areaJson.filter(
            (item) => !["320106", "320116", "320118"].includes(item.code)
          );
          const mergeData = res.flat();
          const data = [...areaData, ...mergeData]
            .filter((item) => item.lon && item.lon !== "0.0")
            .map((item) => {
              return {
                ...item,
              };
            });
          setMarkerData(data, "order");
        });
    } else if (props.api == "largeScreen_orgList") {
      apiMod
        .largeScreen_orgList({
          province: 11,
          city: 199554,
          ...props.paramsObj,
        })
        .then((res) => {
          setMarkerData(res.data);
        });
    } else {
      apiMod[props.api]().then((res) => {
        const max = Math.max(...res.map((item) => item.num));
        const d = res.map((item) => {
          return {
            name: item.name,
            num:item.num,
            itemStyle: {
              areaColor: `rgba(19, 166, 213, ${item.num / max})`,
            },
          };
        });
        areaColorList.value = d.sort((a,b)=>+b.num - +a.num)
        const option = BaseOption([], iconPoint, [25, 25], d);
        mapEl.value?.setOptions(option);
      });
    }
    return;
  }

  if (props.activeTab == "1") {
    apiMod
      .largeScreen_orgList({
        provinceId: 11,
        cityId: 199554,
        ...props.paramsObj
      })
      .then((res) => {
        setMarkerData(res.data);
      });
  } else {
    apiMod
      .dpServiceFacilityList({
        provinceId: 11,
        cityId: 199554,
      })
      .then((res) => {
        setMarkerData(res.data);
      });
  }
};
onMounted(() => {
  getInitData();
});
</script>

<style scoped lang="scss">
:deep(.fav-dialog) {
  .fav-dialog-header {
    color: #fff;
    position: relative;
    z-index: 0;
    padding-left: 20px;
    font-family: "Microsoft YaHei Bold";
    font-weight: 700;
    font-size: 14px;
    letter-spacing: 0.05px;
    color: #fff;
    text-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);

    &::before {
      content: "";
      position: absolute;
      left: 0;
      height: 100%;
      width: 10px;
      z-index: -1;
      background: rgba(253, 189, 0, 1);
    }
  }
}

.timebank-box {
  position: absolute;
  left: 10%;
  bottom:10%;
  display: flex;
  flex-flow: column;
  gap: 10px;
  font-size: 12px;
  li {
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    gap: 10px;
  }
}
</style>
